import {
  Body,
  Controller,
  Delete,
  Get,
  HttpException,
  HttpStatus,
  Param,
  Patch,
  Post,
  Req,
  ServiceUnavailableException,
  UseGuards,
} from '@nestjs/common';
import { UserService } from '../service/user.service';
import { CreateUserDto } from '../dto/user/create-user.dto';
import { UpdateUserDto } from '../dto/user/update-user.dto';
import { Public } from 'src/utils/skip.jwt';
import { LoginUserDto } from '../dto/user/login-user.dot';
import { AuthService } from 'src/auth/auth.service';
import { LocalCustomAuthGuard } from 'src/auth/local-custom-auth.guard';

@Controller('custom/user')
export class UserController {
  constructor(
    private readonly userService: UserService,
    private readonly authService: AuthService,
  ) {}

  @Public()
  @Post('registry')
  async create(@Body() createUserDto: CreateUserDto) {
    if (createUserDto.password !== createUserDto.pwdRepeat) {
      throw new HttpException(
        '两次密码不一致，请重新输入',
        HttpStatus.BAD_REQUEST,
      );
    }
    const isExitUser = await this.userService.findUser(createUserDto.username);
    if (isExitUser) {
      throw new HttpException(
        '当前用户名已经存在，请重新输入',
        HttpStatus.BAD_REQUEST,
      );
    }
    return this.userService.create(createUserDto);
  }

  @Public()
  @UseGuards(LocalCustomAuthGuard)
  @Post('login')
  async login(@Body() loginUserDto: LoginUserDto) {
    try {
      if (!loginUserDto.username) {
        throw new HttpException('账户不能为空', HttpStatus.BAD_REQUEST);
      }

      if (!loginUserDto.password) {
        throw new HttpException('密码不能为空', HttpStatus.BAD_REQUEST);
      }

      const userInfo = await this.userService.findUser(loginUserDto.username);

      if (!userInfo) {
        throw new HttpException(
          '当前用户名不存在，请重新输入',
          HttpStatus.BAD_REQUEST,
        );
      }
      return this.authService.loginCustom(userInfo);
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  @Patch()
  async update(@Req() req, @Body() updateUserDto: UpdateUserDto) {
    return this.userService.update(req.user.userId, updateUserDto);
  }

  // 注销，后期使用token进行注销
  @Delete()
  async remove(@Param('username') username: string) {
    return this.userService.remove(username);
  }

  @Get('userInfo')
  async getUserInfo(@Req() req) {
    return this.userService.findOne(req.user.userId);
  }

  // @Public()
  @Get('info')
  async getInfo(@Req() req) {
    return 'test'
  }
}
